package ch.il07.converter.presentation.beans;

import javax.faces.event.ComponentSystemEvent;
import javax.servlet.http.HttpSession;

import ch.il07.converter.business.ServiceFactoryAdapter;
import ch.il07.converter.business.UserBusiness;
import ch.il07.converter.presentation.AccessControl;
import ch.il07.converter.presentation.Helper;

public class LoginBean {
	private String username = null;
	private String password = null;
	
	private Boolean guest = true;
	
	public String process() {
		String result = "failure";
		
		if(getUsername() != null && getPassword() != null) {
			UserBusiness userImpl = ServiceFactoryAdapter.getUserBusinessInstance();
			if(userImpl.login(getUsername(), getPassword())) {
				HttpSession hs = Helper.getSession();
				guest = false;
				hs.setAttribute("username", getUsername());
				hs.setAttribute("isAdministrator", "" + userImpl.isAdministrator(getUsername(), getPassword()));
				result = "success";
				setPassword("");
			}
		}
		return result;
	}
	
	public String logout() {
		HttpSession hs = Helper.getSession();
		guest = true;
		hs.setAttribute("username", null);
		hs.setAttribute("isAdministrator", null);
		return "logout";
	}
	
	public void forwardToLoginIfNotLoggedIn(ComponentSystemEvent cse) {
		// Authenticated users have access to all pages (page access regardless of the real privileges (member or admin)).
		if(Helper.isAutenthicated()) {
			 return;
		}
		
		if(!AccessControl.isPublicAccessibleFile()) {
			Helper.getFacesContext().getApplication().getNavigationHandler().handleNavigation(Helper.getFacesContext(), null, "/login.xhtml");
		}
	}
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isLoggedIn(){
		return !getGuest();
	}
	
	public boolean getGuest() {
		return guest;
	}

	public void setGuest(Boolean guest) {
		this.guest = guest;
	}
}